package server;

import http.*;

import java.io.*;
import java.net.Socket;

/**
 * 处理客户端请求的线程
 */
public class ClientSocketHandleThread extends Thread {

    private Socket clientConnectSocket;
    private InputStream requestStream;
    private OutputStream outputStream;

    private RequestHandler requestHandler = new RequestHandler();
    private RequestParser requestParser = new RequestParser();
    private ResponseSender responseSender = new ResponseSender();

    ClientSocketHandleThread(Socket clientConnectSocket){
        this.clientConnectSocket = clientConnectSocket;
        try {
            this.requestStream = clientConnectSocket.getInputStream();
            this.outputStream = clientConnectSocket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                //接收请求
                Request request = requestParser.parseRequestStream(requestStream);
                //处理请求
                Response response = requestHandler.handle(request);
                //响应请求
                responseSender.send(response, outputStream);
            }
        } catch (Exception e) {
            try {
                clientConnectSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


}
